package main

import (
	"encoding/json"
	"fmt"
	"gitee.com/baizhige/gin-common-handler/ctxconst"
	"gitee.com/baizhige/gin-common-handler/handler"
	"gitee.com/baizhige/gin-common-handler/params"
	"github.com/gin-gonic/gin"
	"math/rand"
)

// 为了更简洁
var (
	TraceId = params.TraceId
	Path    = params.Path

	Int = params.INT
)

func main() {
	engine := gin.Default()
	engine.Use(Middle) //产生traceId 处理方法结果

	handler.Select(engine)                                                            //选择路由
	handler.POST("/create/user", CreateUser, TraceId(), params.Body[CreateUserReq]()) //注册路由
	handler.GET("/user/query", UserQuery, params.QueryAll[UserQueryReq]())            //一次选择多次使用

	group := engine.Group("/point")                                         //创建Group
	handler.Select(group)                                                   //选择新的路由
	handler.GET("/findById/:id", PointFindById, TraceId(), Path("id", Int)) //演示基础数据类型转换

	engine.Run(":8080")
}

func Middle(ctx *gin.Context) {
	fmt.Println("请求进入！")
	ctx.Set(ctxconst.TraceIdKey, fmt.Sprintf("%v", rand.Int()))
	ctx.Next()
	value, exists := ctx.Get(ctxconst.FuncResult)
	if !exists {
		ctx.JSON(200, Response{
			Code: "200",
			Msg:  "Success",
			Data: nil,
		})
	}
	marshal, _ := json.Marshal(value)
	fmt.Println("存在响应:", string(marshal))
	funcResults := value.([]interface{})
	ctx.JSON(200, Response{"200", "Success", funcResults[0]})
}
